//
//  YJStudentTelCerViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/11/16.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "YJStudentTelCerViewController.h"
#import "loginTextField.h"
#import "YJUserEditViewController.h"
#import "YJSystemCodeViewController.h"
#import "GLPickerView.h"

#define KTEXTFIELDTAG 1000
@interface YJStudentTelCerViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) NSMutableArray *textArray;//显示内容
@property (nonatomic,strong) NSMutableArray *imgArray;//显示图片

@property (nonatomic,copy) NSString *identifyingCode; //获取的验证码
@property (nonatomic,strong) NSMutableArray *textFieldValueArray;//输入框的值
@property(nonatomic,strong)NSTimer *timer;
@property (nonatomic,weak) UIButton *cerButton;//获取验证码

@property (nonatomic,weak) UILabel *personLabel;//显示父亲母亲的label
@end

@implementation YJStudentTelCerViewController
- (NSMutableArray *)textFieldValueArray{
    if (!_textFieldValueArray) {
        _textFieldValueArray = [NSMutableArray array];
    }
    return _textFieldValueArray;
}
- (NSMutableArray *)textArray{
    if (!_textArray) {
        _textArray = [NSMutableArray array];
    }
    return _textArray;
}
- (NSMutableArray *)imgArray{
    if (!_imgArray) {
        _imgArray = [NSMutableArray array];
    }
    return _imgArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.frame = CGRectMake(0, -20, kScreenW, kScreenH + 20);
    self.textFieldValueArray  = [NSMutableArray arrayWithObjects:@"",@"",@"",@"", nil];
    MyLog(@"%@",self.studentInfo);
    
    if (self.telCerRole == KTelCerStudent) {
        self.textArray = [NSMutableArray arrayWithArray:@[self.studentInfo[@"userName"],[NSString stringWithFormat:@"%@ %@%@%@班",self.studentInfo[@"schoolName"],self.studentInfo[@"category"],self.studentInfo[@"academicYear"],self.studentInfo[@"num"]] ,@"输入您的手机号",@"验证码",@"输入新密码",@"请再次输入新密码"]];
        self.imgArray = [NSMutableArray arrayWithArray:@[@"",@"",@"Login_phone",@"Login_Cer",@"Login_Secret",@"Login_Secret"]];
    }else if (self.telCerRole == KTelCerPerson) {
        self.textArray = [NSMutableArray arrayWithArray:@[@"母亲",@"输入您的手机号",@"验证码",@"输入新密码",@"请再次输入新密码"]];
        self.imgArray = [NSMutableArray arrayWithArray:@[@"",@"Login_phone",@"Login_Cer",@"Login_Secret",@"Login_Secret"]];
    }else if (self.telCerRole == KTelCerTeacher){
        self.textArray = [NSMutableArray arrayWithArray:@[self.studentInfo[@"name"],@"输入您的手机号",@"验证码",@"输入新密码",@"请再次输入新密码"]];
        self.imgArray = [NSMutableArray arrayWithArray:@[@"",@"Login_phone",@"Login_Cer",@"Login_Secret",@"Login_Secret"]];
    }
   
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UIButton *backButton = [[UIButton alloc]init];
    backButton.frame = CGRectMake(0, 20, 50, 50);
    [backButton setImage:[UIImage imageNamed:@"black_back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:backButton];
    
    UIImageView *logoImageView = [[UIImageView alloc]init];
    logoImageView.frame = CGRectMake(kScreenW / 3, kScreenH / 7, kScreenW / 3 , kScreenW / 3 );
    logoImageView.contentMode = UIViewContentModeScaleAspectFill;
    logoImageView.image = [UIImage imageNamed:@"Login_sign"];
    [cell.contentView addSubview:logoImageView];
    
    for (int i = 0; i < self.textArray.count; i ++) {
        if (i < (self.telCerRole == KTelCerStudent ? 2:1)) {
            UILabel *textLabel = [[UILabel alloc]init];
            textLabel.frame = CGRectMake(20, kScreenH / 5 + kScreenW / 2/ 3 + 30 + 50 *i, kScreenW - 40 , 40);
            textLabel.text = [NSString stringWithFormat:@"  %@",self.textArray[i]];
            textLabel.userInteractionEnabled = YES;
            textLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
            textLabel.layer.borderWidth = 1;
            textLabel.layer.cornerRadius = 2;
            [cell.contentView addSubview:textLabel];
            if (self.telCerRole == KTelCerPerson) {
                textLabel.userInteractionEnabled = YES;
                [textLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLabel:)]];
                self.personLabel = textLabel;
                
                UIImageView *moreImage = [[UIImageView alloc]init];
                moreImage.frame = CGRectMake(CGRectGetWidth(textLabel.frame) - 20, 17, 10, 6);
                moreImage.image = [UIImage imageNamed:@"arrow_down"];
                [textLabel addSubview:moreImage];
            }
        }else{
            loginTextField *loginTF = [[loginTextField alloc]initWithFrame:CGRectMake(20, kScreenH / 5 + kScreenW / 2/ 3 + 30 + 50 *i, kScreenW - 40 , 40) placeholder:self.textArray[i] imageStr:self.imgArray[i]];
            loginTF.delegate = self;
            loginTF.tag = KTEXTFIELDTAG + i;
            [cell.contentView  addSubview:loginTF];
            if (i == (self.telCerRole == KTelCerStudent ? 3:2) || i == (self.telCerRole == KTelCerStudent ? 2:1)) {
                loginTF.keyboardType = UIKeyboardTypePhonePad;
            }else if (i == (self.telCerRole == KTelCerStudent ? 4:3) || i == (self.telCerRole == KTelCerStudent ? 5:4)) {
                loginTF.secureTextEntry = YES;
                loginTF.keyboardType = UIKeyboardTypeAlphabet;
            }
            if (i == (self.telCerRole == KTelCerStudent ? 3:2)) {
                UIButton *cerButton = [[UIButton alloc]init];
                cerButton.frame = CGRectMake(CGRectGetMaxX(loginTF.frame) - 85, CGRectGetMinY(loginTF.frame) + 5, 80, 30);
                cerButton.backgroundColor = KBACKNAVIGATIONCOLOR;
                [cerButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                [cerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                cerButton.titleLabel.font = [UIFont systemFontOfSize:12];
                cerButton.userInteractionEnabled = YES;
                cerButton.layer.cornerRadius = 2;
                [cerButton addTarget:self action:@selector(getIdentifyingCode) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:cerButton];
                self.cerButton = cerButton;
            }
            if (i == (self.telCerRole == KTelCerStudent ? 5:4) ) {
                //用户协议 @"同意《与时校园用户注册协议》"
                CustomeButton *userAgreementButton = [[CustomeButton alloc]initWithRelativeAlignment:KRelativeAlignmentRight titleNormal:@"同意《与时校园用户注册协议》" imageNormal:@"checkbox_checked" frame:CGRectMake(CGRectGetMinX(loginTF.frame), CGRectGetMaxY(loginTF.frame) + 5 + 5, CGRectGetWidth(loginTF.frame), 20) titleRect:CGRectMake(20, 0, CGRectGetWidth(loginTF.frame), 20) imageRect:CGRectMake(0, 2, 15, 15) textAlignment:NSTextAlignmentLeft font:[UIFont systemFontOfSize:12] titleColor:KHEADERTITLECOLOR];
                [userAgreementButton addTarget:self action:@selector(userAgreement:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:userAgreementButton];
                
                //确定
                CompleteButton *loginButton = [[CompleteButton alloc]initWithFrame:CGRectMake(CGRectGetMinX(userAgreementButton.frame), CGRectGetMaxY(userAgreementButton.frame) + 10, CGRectGetWidth(userAgreementButton.frame), CGRectGetHeight(loginTF.frame)) bgColor:KBACKNAVIGATIONCOLOR tColor:[UIColor whiteColor] text:@"注册"];
                [loginButton addTarget:self action:@selector(roleRegister) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:loginButton];
            }
        }
    }

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kScreenH;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    MyLog(@"%ld",textField.tag - KTEXTFIELDTAG-(self.telCerRole == KTelCerStudent ? 2:1));
    MyLog(@"%@",self.textFieldValueArray);
    MyLog(@"%@",self.textFieldValueArray[0]);
    [self.textFieldValueArray replaceObjectAtIndex:textField.tag - KTEXTFIELDTAG-(self.telCerRole ==KTelCerStudent ? 2:1) withObject:textField.text];
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}

#pragma mark - 获取验证码
- (void)getIdentifyingCode{
    [self.tableView endEditing:YES];
    if (strIsEmpty(self.textFieldValueArray[0])) {
        [Global showActivityWithView:self.view withText:@"请输入手机号"];
        return;
    }
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:self.textFieldValueArray[0] forKey:@"phone"];   //手机号
    [yjNetWorkManger requestType:GET andURL:[JSPathUtil urlAppGetCode] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
//            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response];
//            self.identifyingCode = dic[@"code"];
        }
    }];
    self.cerButton.userInteractionEnabled=NO;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
}
static int count=60;

-(void)handleTimer:(NSTimer *)_timer
{
    //在这里进行处理
    count--;
    if (count==0)
    {
        self.cerButton.userInteractionEnabled=YES;
        [self.cerButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        count=60;
        [self.timer invalidate];
    }
    else
    {
        self.cerButton.userInteractionEnabled=NO;
        [self.cerButton setTitle:[NSString stringWithFormat:@"%ds重新获取",count] forState:UIControlStateNormal];
    }
}

#pragma mark - 注册
- (void)roleRegister{
    [self.tableView endEditing:YES];
    if (strIsEmpty(self.textFieldValueArray[1])) {
        [Global showActivityWithView:self.view withText:@"请输入验证码"];
        return;
    }
    if (strIsEmpty(self.textFieldValueArray[2])) {
        [Global showActivityWithView:self.view withText:@"请输入密码"];
        return;
    }
    if (strIsEmpty(self.textFieldValueArray[3])) {
        [Global showActivityWithView:self.view withText:@"请输入重复密码"];
        return;
    }
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:self.textFieldValueArray[0] forKey:@"phone"];   //手机号
    [dic setValue:self.textFieldValueArray[1] forKey:@"code"];   //验证码
    [dic setValue:self.textFieldValueArray[2] forKey:@"password"];   //密码
    [dic setValue:self.textFieldValueArray[3] forKey:@"repassword"];   //重复密码
    if (!strIsEmpty(self.sysCode)) {
        [dic setValue:self.sysCode forKey:@"sysCode"];   //学生系统码 当type为1 时必填  当为5，6，7时可传多个学校系统码
    }
    if ([self.personLabel.text isEqualToString:@"  父亲"]) {
        [dic setValue:@"2" forKey:@"type"];   // 2 家长-父亲
    }else if ([self.personLabel.text isEqualToString:@"  母亲"]){
        [dic setValue:@"3" forKey:@"type"];   //3 家长-母亲
    }else if ([self.personLabel.text isEqualToString:@"  其他"]){
        [dic setValue:@"4" forKey:@"type"];   //4家长-其他  5与时老师  6大学生志愿者  7学校老师
    }else if ([self.identTeacher isEqualToString:@"  与时老师"]) {
        [dic setValue:@"5" forKey:@"type"];   // 5 与时老师
    }else if ([self.personLabel.text isEqualToString:@"  大学生志愿者"]){
        [dic setValue:@"6" forKey:@"type"];   //6 大学生志愿者
    }else if ([self.personLabel.text isEqualToString:@"  学校老师"]){
        [dic setValue:@"7" forKey:@"type"];   //7学校老师
    }else{
        [dic setValue:@"1" forKey:@"type"];   //1 学生
    }
    
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppRegister] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response];
            [Global setUserTokenInfo:dic[@"token"]]; //
            [JHUserInfo saveUserInfo:dic[@"userInfo"]];
            if (self.telCerRole == KTelCerStudent) {
                //个人编辑页面
                YJUserEditViewController *userEditVC = [[YJUserEditViewController alloc]init];
                userEditVC.userEditRole = KUserEditStudent;
                [self.navigationController pushViewController:userEditVC animated:YES];
            }else if (self.telCerRole == KTelCerPerson){
                YJSystemCodeViewController *systemCodeVC = [[YJSystemCodeViewController alloc]init];
                systemCodeVC.role = KSystemRolePerson;
                [self.navigationController pushViewController:systemCodeVC animated:YES];
            }else if (self.telCerRole == KTelCerTeacher){
                YJUserEditViewController *userEditVC = [[YJUserEditViewController alloc]init];
                userEditVC.userEditRole = KUserEditTeacher;
                [self.navigationController pushViewController:userEditVC animated:YES];
            }
            
        }
    }];
}
#pragma mark - 选择父亲，母亲，其他
- (void)tapLabel:(UITapGestureRecognizer *)tap{
    GLPickerView *pickView= [[GLPickerView alloc]initDatePackerWithDataArray:@[@"父亲",@"母亲",@"其他"] Response:^(NSString *title) {
        self.personLabel.text = [NSString stringWithFormat:@"  %@",title];
    }];
    [pickView show];
}
#pragma mark - 同意用户协议
- (void)userAgreement:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    [sender setImage:sender.selected ? [UIImage imageNamed:@"checkbox_unchecked"]:[UIImage imageNamed:@"checkbox_checked"] forState:UIControlStateNormal];
}
#define mark - 返回
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
